#!/usr/bin/perl -w
use strict;

$\="\n";
#my $ord=fork?0:1;
chdir '/usr/Sky/down';
use protect;
use DBI;

our $h=DBI->connect('DBI:mysql:database=Down','root') || die $DBI::errstr;

our $ns=$h->prepare(qq/select id,url,filename,post,size,nowsize from down where status in (0) order by prio desc,(rand()+0.5)*(size+1)/);

my ($id,$url,$sz,$fn,$post,$a,$s1,$s2);
chdir 'in';
my $st=0;
$ns->execute();

my (@w);

while (($id,$url,$fn,$post,$s1,$s2)=$ns->fetchrow_array())
{
next unless $url;
#next if (($id & 1) == $ord);
$url=~s{ftp\.efind}{ftpr.efind}g; # sorry - no risk

protect::DO(\$url);#=~s{([^\w.\-\+_=\?\&:/@!%])}{'%'.unpack('H2',$1)}eg;
$a='';

protect::DO(\$fn),#=~s{([^\w.\-\+_=\?\&:/@!%])}{'%'.unpack('H2',$1)}eg,
$a.="--output-document='$fn' "
if defined($fn) && $fn ne '';

protect::DO(\$post),#=~s{([^\w.\-\+_=\?\&:/@!%])}{'%'.unpack('H2',$1)}eg,

$a.="--post-data='$post' "
if defined($post) && $post ne '';

#print "wget -dc '$url' $a --proxy=off --progress=dot:binary"," # id:$id of $s1";
print "$url#id:$id,$s1";
$st+=$s1;

#$w[$id&1]+=$s1;

}

my $sm=$st/1024/1024;
printf "%u (%.3f Mb, %.1f kbps, %.2f руб)\n",$st,$sm,$st*8/4/60/60/1000,$sm*.2;
#$w[2]=$w[1]-$w[0];
#print "Worker 1: $w[0]; Worker 2: $w[1]; diff: $w[2]\n";
# 32.6 rub = 1 y.e.
#    64 = 3 = 10 (kop)
#   125 = 4 = 13
#   250 = 5 = 16.4
#   500 = 6 = 20
#  1000 = 7 = 23
#  2000 = 8 = 26
#  3000 = 9 = 29.4
#  4000 =10 = 32.6
#  5000 =11 = 36
